//
//  ProcessedOrderSearch.m
//  rrbi
//
//  Created by mac book on 2019/3/21.
//

#import "ProcessedOrderSearch.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "HandleOrderHeader.h"
#import "OrderManagementCell.h"
#import "FBOrderDetalisViewController.h"
#import "OrderManagementModel.h"
#import "KnightEvaluateViewController.h"

@interface ProcessedOrderSearch ()<HandleOrderHeaderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate,UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,assign) NSInteger page;

@property (nonatomic, strong) NSMutableArray *mainArray;
@property (nonatomic, strong) UITextField *searchTextFiled;

@property (nonatomic, strong) NSString *searchStr;

@end

@implementation ProcessedOrderSearch

- (NSMutableArray *)mainArray {
    if (!_mainArray) {
        _mainArray = [NSMutableArray array];
    }
    return _mainArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.searchStr = @"-1";
    
    [self creatCustomNavView];

    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT- HitoTopHeight) style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderManagementCell class]) bundle:nil] forCellReuseIdentifier:@"orderManagementCell"];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreData)];
   

}

#pragma mark - 数据请求
-(void)getData{
    [self.tableView setContentOffset:CGPointMake(0,0) animated:YES];
    [self getDataWithPageNum:1 isHeader:YES];
}

-(void)getMoreData{
    
    [self getDataWithPageNum:self.page isHeader:NO];
    
}
#pragma mark =====================================================  Data source
- (void)getDataWithPageNum:(NSInteger)pageNum isHeader:(BOOL)isHeader {
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{
                          @"ince":@"get_order_list",
                          @"sid":[UserModel sharedInstanced].ru_Id,
                          @"page":[NSString stringWithFormat:@"%ld",(long)pageNum],
                          @"keyword":self.searchStr
                          };
    
    NSString *URL = [NSString stringWithFormat:@"%@%@",BaseUrl,@"get_order_list"];
    [mgr POST:URL parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            
            NSMutableArray *tempArr = [NSMutableArray array];
            tempArr = [OrderManagementModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:@"data"]];
            
            if (isHeader) {
                self.page = 1;
                self.tableView.mj_footer.state = MJRefreshStateIdle;
                [self.mainArray removeAllObjects];
                [self.mainArray addObjectsFromArray:tempArr];
                
                self.page++;
            }else {
                [self.tableView.mj_footer endRefreshing];
                if (tempArr.count > 0) {
                    [self.mainArray addObjectsFromArray:tempArr];
                    self.page++;
                }else{
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [self.tableView reloadData];
            
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        if (isHeader) {
            [self.tableView.mj_header endRefreshing];
            self.page = 1;
        }else {
            [self.tableView.mj_footer endRefreshing];
            self.page--;
        }
        [self hidHUD:@"网络异常"];
    }];
    
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.mainArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderManagementCell *cell = [tableView dequeueReusableCellWithIdentifier:@"orderManagementCell"];
    OrderManagementModel *model = self.mainArray[indexPath.row];
    [cell updataDataWithModel:model];
    __weak typeof(self) weakSelf = self;
    cell.xianQingButtonBlock = ^{
        FBOrderDetalisViewController *vc = [[FBOrderDetalisViewController alloc]init];
        vc.order_id = model.order_id;
        vc.order_type = 2;
        vc.isGuanLi = YES;
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    cell.evaluationButtonBlock = ^{
        [weakSelf evaluationButtonClick:model];
    };
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    OrderManagementModel *model = self.mainArray[indexPath.row];
    
    if (model.delivery.count <= 0) {
        if ([model.pj_status isEqualToString:@"1"]) {//已完成
            return 260;//有评价无骑手
        } else {
            return 220;//没有评价无骑手
        }
    } else {
        if ([model.pj_status isEqualToString:@"1"]) {//已完成
            return 310;//有评价有骑手
        } else {
            return 285;//没有评价有骑手
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.00001;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}


//去评论按钮点击
- (void)evaluationButtonClick:(OrderManagementModel *)model {
    
    NSString *order_sn= model.order_sn;
    
    KnightEvaluateViewController *vc= [[KnightEvaluateViewController alloc]init];
    vc.order_sn  = order_sn;
    [self.navigationController pushViewController:vc animated:YES];
    
}

-(void)creatCustomNavView{
    //  顶部搜索
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    self.navigationItem.titleView = topView;
    if (@available(iOS 11.0, *)) {
        [topView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(240);
            make.height.mas_equalTo(44);
        }];
    }
    
    
    [topView addSubview:self.searchTextFiled];
    [self.searchTextFiled mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(topView.mas_centerX);
        make.centerY.equalTo(topView.mas_centerY);
        make.width.mas_equalTo(240 / WIDTH_6S_SCALE);
        make.height.mas_equalTo(35 / HEIGHT_6S_SCALE);
    }];
    
    
    
    //icon_seach
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelButtonClick)];
    
}

-(void)cancelButtonClick{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
#pragma mark - init
- (UITextField *)searchTextFiled
{
    if (!_searchTextFiled) {
        _searchTextFiled = [[UITextField alloc]init];
        _searchTextFiled.backgroundColor = [UIColor clearColor];
        _searchTextFiled.backgroundColor = getColor(@"F3F4F7");
        _searchTextFiled.font = [UIFont systemFontOfSize:14];
        _searchTextFiled.textColor = getColor(textColor);
        _searchTextFiled.textAlignment = NSTextAlignmentLeft;
        _searchTextFiled.placeholder = @"请输入订单相关信息";
        _searchTextFiled.layer.cornerRadius = 5;
        _searchTextFiled.layer.masksToBounds = YES;
        _searchTextFiled.delegate = self;
        _searchTextFiled.returnKeyType = UIReturnKeySearch;//变为搜索按钮
        _searchTextFiled.clearButtonMode = UITextFieldViewModeAlways;
        _searchTextFiled.enablesReturnKeyAutomatically = YES; //这里设置为无文字就灰色不可点
        
        
        //创建左侧视图
        UIView *lv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 50)];//宽度根据需求进行设置，高度必须大于 textField 的高度
        lv.backgroundColor = [UIColor clearColor];
        UIImageView *leftImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search_small"]];
        leftImage.frame = CGRectMake(0, 0, 18, 18);
        leftImage.center = lv.center;
        [lv addSubview:leftImage];
        
        //设置 textField 的左侧视图
        //设置左侧视图的显示模式
        _searchTextFiled.leftViewMode = UITextFieldViewModeAlways;
        _searchTextFiled.leftView = lv;
        
    }
    return _searchTextFiled;
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    NSString *str = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (str.length ==0) {
        return;
    }else{
        
        self.searchStr = str;
        [self getData];
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    
    [textField resignFirstResponder];
    return YES;
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
